//
//  DataManager.swift
//  Notepad
//
//  Created by 左忠飞 on 2021/1/20.
//

import UIKit
import SQLiteSwift3

class DataManager: NSObject {
    //创建一个数据库操作对象属性
    static var sqlhandle:SQLiteSwift3?
    
    //标记是否打开数据库
    static var isOpen = false
    
    //打开数据库的方法
    class func openDataBase(){
        //获取沙盒路径
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        //进行文件名的拼接
        let file = path + "/DataBase.sqlite"
        //打开数据库,如果数据库不存在就会进行创建
        sqlhandle = SQLiteSwift3.openDB(file)
        //设置数据库打开表示
        isOpen = true
    }
    
    //提供一个队分组数据进行存储的类方法
    class func saveGroup(name:String){
        //判断数据库有没有打开,如果没有,打开数据库操作
        if !isOpen {
            self.openDataBase()
        }
        //创建一个数据表字段对象
        let key = SQLiteKeyObject()
        //设置字段名
        key.name = "groupName"
        //设置字段名为字符串
        key.fieldType = TEXT
        //将字段修饰为唯一
        key.modificationType = UNIQUE
        //进行分组表的创建,如果已经存在,则不执行任何操作
        sqlhandle?.createTable(withName: "groupTable", keys: [key])
        //进行数据的插入
        sqlhandle?.insertData(["groupName":name], intoTable: "groupTable")
    }
    
    //提供一个获取所有分组数据的类方法
    class func getGroupData()->[String]{
        if !isOpen {
            self.openDataBase()
        }
        //创建查询请求对象
        let request = SQLiteSearchRequest()
        //查询结果容器数组
        var array = Array<String>()
        //进行数据查询操作
        sqlhandle?.searchData(withReeuest: request, inTable: "groupTable", searchFinish: { (success, dataArray) in
            //遍历查询到的数据,赋值进结果数组中
            dataArray?.forEach({ (element) in
                array.append(element.values.first! as! String)
            })
        })
        return array
    }
    
    //添加记事的方法
    class func addNote(note:NoteModel) {
        if !isOpen {
            self.openDataBase()
        }
        //创建记事表
        self.createNoteTable()
        
        //将记事模型转换成字典进行存表
        let result = sqlhandle?.insertData(note.toDictionary(), intoTable: "noteTable")
        
        print("添加记事\(result! ? "成功" : "失败")")
    }
    
    //根据分组获取记事的方法
    class func getNote(group:String) ->  [NoteModel] {
        if !isOpen {
            self.openDataBase()
        }
        //创建查询请求
        let request = SQLiteSearchRequest()
        //设置查询条件
        request.contidion = "ownGroup=\"\(group)\""
        
        var array = Array<NoteModel>()
        sqlhandle?.searchData(withReeuest: request, inTable: "noteTable", searchFinish: { (success, dataArray) in
            dataArray?.forEach({ (element) in
                let note = NoteModel()
                //对记事模型进行赋值
                note.title = element["time"] as! String?
                note.title = element["title"] as! String?
                note.body = element["body"] as! String?
                note.group = element["group"] as! String?
                note.noteId = element["noteId"] as! Int?
                array.append(note)
            })
        })
        
        return array
    }
    //创建记事表
    class func createNoteTable(){
        let noteId = SQLiteKeyObject()
        noteId.name = "noteId"
        noteId.fieldType = INTEGER
        
        //将noteId作为主键
        noteId.modificationType = PRIMARY_KEY
        
        let ownGroup = SQLiteKeyObject()
        ownGroup.name = "ownGroup"
        ownGroup.fieldType = TEXT
        
        let body = SQLiteKeyObject()
        body.name = "body"
        body.fieldType = TEXT
        body.tSize = 400
        
        let title = SQLiteKeyObject()
        title.name = "title"
        title.fieldType = TEXT
        
        let time = SQLiteKeyObject()
        time.name = "time"
        time.fieldType = TEXT
        
        let result = sqlhandle?.createTable(withName: "noteTable", keys: [noteId,ownGroup,body,title,time])
        
        print("创建记事表:\(result! ? "成功" : "失败")")
    }
    
    //更新一条记事内容
    class func updateNote(note:NoteModel){
        if !isOpen {
            self.openDataBase()
        }
        
        //根据主键ID来进行更新
        sqlhandle?.updateData(note.toDictionary(), intoTable: "noteTable", while: "noteId = \(note.noteId)", isSecurity: true)
    }
    
    //删除一条记事
    class func deleteNote(note:NoteModel){
        if !isOpen {
            self.openDataBase()
        }
        sqlhandle?.deleteData("noteId=\(note.noteId!)", intoTable: "noteTable", isSecurity: true)
    }
    //删除一个分组,将其中所有记事删除
    class func deleteGroup(name:String){
        if !isOpen {
            self.openDataBase()
        }
        //先删除分组下所有记事
        sqlhandle?.deleteData("ownGroup=\"\(name)\"", intoTable: "noteTable", isSecurity: true)
        //在删除分组
        sqlhandle?.deleteData("GroupName=\"\(name)\"", intoTable: "groupTable", isSecurity: true)
    }
}
